<template>
  <div class="waterfall-container">
    <div ref="waterfallRef" class="waterfall-wrapper">
      <div @click.stop="go_detail(item.id)" v-for="(item, index) in positionedItems" :key="item.id" class="waterfall-item"
        :style="{
          width: columnWidth + 'px',
        }">
      <!-- <div v-for="(item, index) in positionedItems" :key="item.id" class="waterfall-item"
        :style="{
          width: columnWidth + 'px',
          position: 'absolute',
          top: item.top + 'px',
          left: item.left + 'px'
        }"> -->
        <div class="video-card">
          <div class="video-wrapper" @mouseenter="hoveredIndex = index" @mouseleave="hoveredIndex = -1">
            <video 
              ref="videoRefs"
              :src="item.url" 
              :poster="item.cover" 
              preload="metadata"
              muted
              loop
              @click="togglePlay(index)"
            ></video>
            <div v-if="hoveredIndex !== index" class="video-play-overlay">
              <svg-icon icon-class="play"></svg-icon>
            </div>
          </div>
          <div class="video-info">
            <div class="video-title">{{ item.name }}</div>
            <div class="video-meta">
              <div class="author-info">
                <img 
                  :src="item.avatar || 'default-avatar.png'" 
                  class="author-avatar" 
                  alt="作者头像"
                />
                <span class="author-nickname">{{ item.userName }}</span>
              </div>
              <span class="likes">{{ item.likeNum || 0 }} ❤</span>
            </div>
          </div>
        </div>
        <div class="clear"></div>
      </div>
      <div class="clear"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  columnCount: {
    type: Number,
    default: 3
  },
  columnGap: {
    type: Number,
    default: 25
  },
  rowGap: {
    type: Number,
    default: 25
  }
})

const emit = defineEmits(['load'])

const waterfallRef = ref(null)
const videoRefs = ref([])
const containerWidth = ref(0)
const containerHeight = ref(0)
const columnWidth = ref(0)
const positionedItems = ref([])
const hoveredIndex = ref(-1)

const togglePlay = (index) => {
  if (videoRefs.value[index]) {
    const video = videoRefs.value[index]
    if (video.paused) {
      video.play()
    } else {
      video.pause()
    }
  }
}

const calculateLayout = () => {
  if (!waterfallRef.value) return

  // 固定列宽为370px
  const fixedColumnWidth = 370
  const columnCount = props.columnCount
  const columnGap = props.columnGap
  const rowGap = props.rowGap

  // 计算容器总宽度
  containerWidth.value = waterfallRef.value.clientWidth
  columnWidth.value = fixedColumnWidth

  // 计算实际可用宽度和居中偏移
  const totalColumnsWidth = columnCount * fixedColumnWidth + (columnCount - 1) * columnGap
  const leftOffset = containerWidth.value > totalColumnsWidth 
    ? (containerWidth.value - totalColumnsWidth) / 2 
    : 0

  // 初始化列高度
  const columnHeights = new Array(columnCount).fill(0)

  // 位置计算
  const positioned = props.items.map((item, index) => {
    // 找到最短的列
    const shortestColumnIndex = columnHeights.indexOf(Math.min(...columnHeights))
    
    // 计算位置
    const left = leftOffset + shortestColumnIndex * (fixedColumnWidth + columnGap)
    const top = columnHeights[shortestColumnIndex]

    // 更新列高度（使用最小和最大高度）
    const infoHeight = 120  // 信息区域高度

    const totalItemHeight = 651 + infoHeight + rowGap

    columnHeights[shortestColumnIndex] += totalItemHeight

    // 更新容器高度
    containerHeight.value = Math.max(...columnHeights)

    return {
      ...item,
      left,
      top,
      width: fixedColumnWidth
    }
  })

  positionedItems.value = positioned
}

const onVideoLoad = (index) => {
  emit('load', index)
}

const handleResize = () => {
  calculateLayout()
}

const go_detail = (id) => {
  router.push({ name: 'video-detail', params: { id: id } })
}

onMounted(() => {
  calculateLayout()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 监听items变化重新布局
watch(() => props.items, () => {
  nextTick(calculateLayout)
}, { deep: true })
</script>

<style lang="less" scoped>
.waterfall-container {
  // width: 100%;
  position: relative;
  height: auto;
  // max-width: 1600px;
  // margin: 0 auto;
  .clear {
    clear: both;
  }
  .waterfall-wrapper {
    position: relative;
    height: auto;
    display: flex;
    flex-wrap: wrap;
    gap: 25px;

    .waterfall-item {
      box-sizing: border-box;
      // margin-bottom: 25px;
      background: #f5f5f5;
      border-radius: 8px;
      overflow: hidden;
      transition: transform 0.3s ease;

      &:hover {
        transform: scale(1.02);
        box-shadow: 0 4px 10px rgba(0,0,0,0.1);
      }

      .video-card {
        width: 370px;
        display: flex;
        flex-direction: column;

        .video-wrapper {
          position: relative;
          
          video {
            width: 370px;
            height: 651px;
            object-fit: cover;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            cursor: pointer;
          }

          .video-play-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            background: rgba(0,0,0,0.3);
            opacity: 0;
            transition: opacity 0.3s;
            cursor: pointer;
            font-size: 48px;
            &:hover {
              opacity: 1;
            }
          }

          
        }

        .video-info {
          width: 370px;
          padding: 10px;
          background: #141414;
          height: 100px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .video-title {
            font-weight: bold;
            margin-bottom: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: white;
            font-size: 14px;
          }

          .video-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #888;
            font-size: 12px;

            .author-info {
              display: flex;
              align-items: center;

              .author-avatar {
                width: 39px;
                height: 39px;
                border-radius: 50%;
                margin-right: 8px;
                object-fit: cover;
              }

              .author-nickname {
                color: #aaa;
                max-width: 150px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-size: 12px;
              }
            }

            .video-views {
              color: #aaa;
            }

            .likes {
              font-size: 16px;
              color: #ff4081;
            }
          }
        }
      }
    }
  }
}
</style>